package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.domain.Account;
import com.example.domain.Admin;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Autowired
    AdminMapper adminMapper;

    //    查全部数据
    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    //    查单个数据
    public Admin selectByPrimaryKey(Long id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    //    分页查询
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

    // 新增数据---注册
    public void add(Admin admin) {
        String username = admin.getUsername();
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin != null){    //账号存在，无法注册
            throw new CustomException("500","账号存在，无法注册");
        }
        if (StrUtil.isBlank(admin.getPassword())){   //密码没填
            admin.setPassword("abc");    //默认密码
        }

        admin.setRole("ADMIN");    //设置角色

        adminMapper.insert(admin);
    }

    //根据id 更新数据
    public void update(Admin admin) {

        adminMapper.updateByPrimaryKey(admin);

    }

    //根据id  删除数据
    public void deleteById(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    //    管理员用户登录
    public Admin login(Account account) {
        String username = account.getUsername();    //账号
        Admin dbAdmin = adminMapper.selectByUsername(username);

        if (dbAdmin == null){    //没查询到用户
            throw new CustomException("500","没有此用户");
        }
//      数据库存在这个账号
        String password = account.getPassword();
        if (!dbAdmin.getPassword().equals(password)){    //密码错误
            throw new CustomException("500","密码错误");
        }
        return dbAdmin;
    }

//管理员登录修改密码
    public void updatePassword(Account account) {
        Integer id = account.getId();
        Admin admin = this.selectByPrimaryKey(Long.valueOf(id));
        if (!admin.getPassword().equals(account.getPassword())){     //页面传来的原密码跟数据库对比，不匹配就报错
            throw new CustomException("500","对不起，原密码错误");
        }
        admin.setPassword(account.getNewPassword());           //设置新密码
        this.update(admin);
    }

}
